#include "BaiduLogin.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#include "BaiduToken.h"

BaiduLogin::BaiduLogin(QObject *parent)
    : QObject{parent}
{
    client_id = BaiduToken::client_id;
    qDebug() << "BaiduLogin" << client_id;
}

bool BaiduLogin::loginSucess(QString url)
{
    //登录成功保存登录信息
    if(url.indexOf("login_success") != -1){
        url = url.mid(url.indexOf("#") + 1, -1);
        QJsonObject json;
        qsizetype pos = url.indexOf("=");
        //qDebug("qsizetype %d", pos);
        //解析字符串
        while(pos != -1){
            QString k = url.mid(0, pos);
            url = url.mid(pos + 1, -1);
            pos = url.indexOf("&");
            QString v = url.mid(0, pos);
            url = url.mid(pos + 1, -1);
            //qDebug("kv %s %s", k.toStdString().c_str(), v.toStdString().c_str());
            QJsonValue jv(v);
            json.insert(k, jv);
            pos = url.indexOf("=");
        }
        //保存json文件
        QJsonDocument jdoc(json);
        QByteArray qba = jdoc.toJson(QJsonDocument::Compact);
        //qDebug(qba);
        QFile uf = QFile(QStringLiteral("user.json"));
        uf.open(QIODevice::ReadWrite);
        uf.resize(0);
        uf.write(qba);
        uf.close();
        BaiduToken::checkCache();
        return true;
    }
    return false;
}
